const bcrypt = require('bcryptjs');
const {getUserInfo} = require('../service/user.service')
const {UserRegisterError,UserinfoValidator,userIsundefined,userPasswordError,userLoginError} = require('../consitant/err.type')

//密码加密
const crpytpassword = async (ctx,next) =>{
try{

  const {password} = ctx.request.body;

  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(password,salt);
 
  ctx.request.body.password = hash
  await next();

}catch(err){
  console.error(err)
}
}

const userinfoValidator = async (ctx,next) => {
  const {user_name} = ctx.request.body;

  if(await getUserInfo({user_name})){
    ctx.app.emit('error',UserinfoValidator,ctx)
    return 
  }

  await next();
}

//参数验证中间件
const validator =  (rules) =>{

  return async(ctx,next) => {
    try {

      await ctx.verifyParams(rules)

    }catch(err){

      console.error(err)
      UserRegisterError.result = err
      return ctx.app.emit('error',UserRegisterError,ctx)

    }
    await next();
  }

}

//登录验证用户是否存在与密码是否正确
const verifyLogin = async(ctx,next) =>{
  try{
    const {user_name,password} = ctx.request.body;
    let res = await getUserInfo({user_name});
    //用户不存在
    if(!res){
      console.error('用户不存在',ctx.request.body);
      ctx.app.emit('error',userIsundefined,ctx)
    }
    //验证密码是否正确
    if(!bcrypt.compareSync(password,res.password)){
      ctx.app.emit('error',userPasswordError,ctx);
      return 
    }
  }catch(err){
    console.error(err);
    ctx.app.emit('error',userLoginError,ctx)
  }
  await next();
}

module.exports = {
  validator,
  crpytpassword,
  userinfoValidator,
  verifyLogin
}